package C053;

import java.util.Arrays;

/**
 * ClassName: C02
 * Package: C053
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/2/21 11:15
 * @Version 1.0
 * @Since 1.0
 */
public class C02 {

    public static void main(String[] args) {
        //System.out.println(removeDuplicateLetters("bcabc"));
        System.out.println(removeDuplicateLetters("cbacdcbc"));
    }

    static char[] charArray;
    static int[] count = new int[26];
    static int MAXLEN = 10001, r;
    static char[] stack = new char[MAXLEN];

    // 记录是否出现过
    static boolean[] enter = new boolean[26];

    public static String removeDuplicateLetters(String s) {
        charArray = s.toCharArray();
        r = 0;
        Arrays.fill(count, 0);
        Arrays.fill(enter, false);
        for (int i = 0; i < charArray.length; i++) {
            count[charArray[i] - 'a']++;
        }

        // 初始化栈
        for (int i = 0; i < charArray.length; i++) {
            if (!enter[charArray[i] - 'a']) {
                while (r > 0 && charArray[i] < stack[r - 1] && count[stack[r - 1] - 'a'] > 0 ) {
//                    count[charArray[stack[r - 1] - 'a'] - 'a']--;
                    enter[stack[r - 1] - 'a'] = false;
                    r--;
                }
                stack[r++] = charArray[i];
                enter[charArray[i] - 'a'] = true;
            }
            count[charArray[i] - 'a']--;
        }

        return new String(stack, 0, r);
    }
}
